#!/usr/bin/env bash
# artix.sh - Artix installation script
#
## License
#
# Copyright (c) 2021 Damon Kwok <damon-kwok@outlook.com>
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
#
## About
#
# While this script does assist with installing Gentoo, it is NOT a
# replacement for reading and understanding the Gentoo Handbook for
# your system.  See https://gentoo.org/docs/gettingstarted.html for
# information on getting started with Gentoo.
#
# This file uses inline documentation whenever possible to preserve
# context, situational or otherwise.  Please read the entire file
# before continuing to ensure you are aware of how this script
# functions, as undesired behaviors for your use-case may exist.
#
# This script does NOT automatically partition your disk(s).  You MUST
# partition and mount your disk(s) before running this script.
#
##

set -e -o pipefail

alias fold="fold -s -w ${COLUMNS:-$(stty size|awk '{print $2}')}"
alias make="make -s -j $(grep -c ^processor /proc/cpuinfo)"

# Width-respecting print
OS_NAME="Artix"
print() {
  echo "<><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>"
  echo "<> ${OS_NAME}: $@" | fold
  #echo "<><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>"
  echo ""
}

# This section describes variables that will define the resulting
# system.  Some are specific to this script, though others should look
# familiar, aside from their prefix.
#
#   ARTIX_CONFIG_URL
#
#       The base URL where the source of this repository (or your fork)
#       is available.  This allows this script to download all needed
#       configuration files rather than you having to retrieve them
#       manually.
#
#   ARTIX_HOSTNAME
#
#       The hostname to set on the resulting system after the
#       installation has completed.
#
#   ARTIX_LOCALE
#
#       The LOCALE to set based on your preference.  All language
#       defaults such as this default to some variant of en_US.UTF-8
#       for simplicity of design.
#
#   ARTIX_VIDEO_CARDS
#
#       The value of VIDEO_CARDS that will be set in
#       '/etc/portage/make.conf', which may either be left blank or be
#       configured as mentioned in the following url:
#
#       https://wiki.gentoo.org/wiki//etc/portage/make.conf#VIDEO_CARDS
#
#       You most likely should use "amdpu", "intel", or "nvidia".
#
#   ARTIX_TIMEZONE
#
#       The timezone to set on the resulting system after the
#       installation has completed.  This is set to America/New_York
#       by default for simplicity of design.

ARTIX_CONFIG_URL="https://gitee.com/damon-kwok/artix/raw/main"
ARTIX_HOSTNAME="artix"
ARTIX_LOCALE="en_US.UTF-8 UTF-8"
ARTIX_TIMEZONE="Asia/Shanghai"
ARTIX_VIDEO_CARDS="virtualbox"
ARTIX_INIT="openrc"

# This section describes how the kernel will be built, and whether the
# user will be prompted to configure their kernel. The two mentioned
# variables may be used together to suit a variety of use-cases.
#
#   ARTIX_KERNEL_AUTOBUILD
#
#     When 'true', this implies that the user does not want to perform
#     any manual configuration of the kernel, regardless of whether a
#     configuration file was provided. '$ make menuconfig' will NOT be
#     run before compiling the kernel.
#
#     When any value OTHER than 'true', this implies that the use DOES
#     want to perform manual configuration on the kernel, regardless
#     of whether a configuration file was provided. '$ make menuconfig'
#     will be run before compiling the kernel.

ARTIX_KERNEL_AUTOBUILD="true"


# TODO: I would like this section to be where a user defines their
# partition schema, specifically for configuring GRUB2.
#
#   ARTIX_PARTITION_BOOT
#
#       Missing description
#
#   ARTIX_PARTITION_SWAP
#
#       Missing description
#
#   ARTIX_PARTITION_SWAPFILE_SIZE
#
#       The size of the swapfile to create.  This is only used if
#       ARTIX_PARTITION_SWAP is set to "/swapfile", and defaults to 4G.

ARTIX_PARTITION_BOOT="/dev/sda"
ARTIX_PARTITION_SWAP="/dev/sda2"
ARTIX_PARTITION_SWAPFILE_SIZE="20G"
ARTIX_PARTITION_ROOT="/dev/sda3"


OUT_PREREQUISITES() {
  if [ -v "$ARTIX_PARTITION_BOOT" ]; then
    print "error: ARTIX_PARTITION_BOOT is not set!"
    print "Exiting..."
    exit 1
  fi

  AUTO_MOUNT $ARTIX_PARTITION_ROOT /mnt/artix

  if [ ! -e /mnt/artix ]; then
    print "error: '/mnt/artix' does not exist!"
    print "Exiting..."
    exit 1
  fi
}

OUT_BOOTSTRAP() {
  print "Connect to the internet"
  ping baidu.com -c 3

  #if [ -n "$(command -v ntpd)" ]; then
  #    ntpd -q -g
  #else
  #    print "warning: ntpd not found!"
  #    print "assuming system time is correct"
  #fi

  print "Set the keyboard layout:"
  loadkeys us
  FONT_MAP=
  FONT=
  KEYMAP=us

  if [ ! -d /mnt/artix/usr/ ]; then
    print "Extracting Stage3 tarball..."

    sed -i 's/Server =/#Server =/g' /etc/pacman.d/mirrorlist
    sed -i 's/#Server = https:\/\/mirrors.tuna/Server = https:\/\/mirrors.tuna/g' /etc/pacman.d/mirrorlist
    sed -i 's/#Server = https:\/\/mirrors.ustc/Server = https:\/\/mirrors.ustc/g' /etc/pacman.d/mirrorlist
    sed -i 's/#Server = https:\/\/mirrors.cloud.tencent/Server = https:\/\/mirrors.cloud.tencent/g' /etc/pacman.d/mirrorlist

    case "${ARTIX_INIT}" in
      "dinit"|"openrc"|"runit")
        basestrap /mnt/artix base base-devel ${ARTIX_INIT} elogind-${ARTIX_INIT} linux \
                  linux-firmware intel-ucode amd-ucode iucode-tool \
		              sof-firmware alsa-firmware alsa-utils-${ARTIX_INIT} ;;
      "s6")
        basestrap /mnt/artix base base-devel s6-base elogind-${ARTIX_INIT} linux \
                  linux-firmware intel-ucode amd-ucode iucode-tool \
		              sof-firmware alsa-firmware alsa-utils-${ARTIX_INIT} ;;
      "66")
        basestrap /mnt/artix base base-devel 66 elogind-${ARTIX_INIT} linux \
                  linux-firmware intel-ucode amd-ucode iucode-tool \
		              sof-firmware alsa-firmware alsa-utils-${ARTIX_INIT} ;;
      *)
        basestrap /mnt/artix base base-devel systemd elogind linux \
                  linux-firmware intel-ucode amd-ucode iucode-tool \
		              sof-firmware alsa-firmware alsa-utils ;;
    esac

    # basestrap /mnt/artix base base-devel openrc # elogind-openrc
    # basestrap /mnt/artix base base-devel runit # elogind-runit
    # basestrap /mnt/artix base base-devel s6-base # elogind-s6
    # basestrap /mnt /artixbase base-devel 66 # elogind-suite66
    # basestrap /mnt/artix base base-devel systemd # elogind

    # print "Install kernel:"
    # basestrap /mnt/artix linux linux-firmware intel-ucode amd-ucode iucode-tool
    # basestrap /mnt/artix linux-lts linux-firmware

    # print "fstabgen:"
    # fstabgen -U /mnt/artix >> /mnt/artix/etc/fstab
  fi
}

OUT_DOWNLOAD_CONF() {
  cp -f artix.sh /mnt/artix/
  print "Downloading portage configuration files..."
  config_files="
    #    etc/portage/make.conf
    #    etc/portage/sets/xin-base
    #    etc/portage/sets/xin-nscde
    #    etc/portage/sets/xin-cinnamon
    #    etc/portage/sets/xin-workstation
    etc/pacman.d/mirrorlist-arch
    root/.config/i3/config
    usr/share/backgrounds/archlinux1.jpg
    usr/share/backgrounds/archlinux2.png
    usr/share/backgrounds/archlinux3.png
    usr/share/backgrounds/archlinux4.jpg
    "

  for config_file in $config_files; do
    local config_dir="`dirname /mnt/artix/$config_file`"
    [ -e ${config_dir} ] && [ ! -d ${config_dir} ] && rm ${config_dir}
    mkdir -p ${config_dir}
    [ -e "/mnt/artix/$config_file" ] && rm -rf "/mnt/artix/$config_file"
    # wget -q "$ARTIX_CONFIG_URL/$config_file" -O "/mnt/artix/$config_file"
    curl -s -o "/mnt/artix/$config_file" "$ARTIX_CONFIG_URL/$config_file"
  done; unset config_dir config_files config_file

  #print "Updating make.conf..."
  #sed -i "
  #    s/^MAKEOPTS.*$/MAKEOPTS\=\"-j$(grep -c ^processor /proc/cpuinfo)\"/;
  #    s/^VIDEO_CARDS.*$/VIDEO_CARDS=\"$ARTIX_VIDEO_CARDS\"/;
  #" /mnt/artix/etc/portage/make.conf

  # print "Copying '/etc/resolv.conf'..."
  # echo "nameserver 8.8.8.8" > /mnt/artix/etc/resolv.conf

  #echo "select china mirrors:"
  #mirrorselect -i -o >> /mnt/artix/etc/portage/make.conf

  # print "Copying '/etc/resolv.conf'..."
  # cp --dereference /etc/resolv.conf /mnt/artix/etc/

  # print "Copying /usr/lib/grub/x86_64-efi/"
  # cp --dereference /usr/lib/grub/ /mnt/artix/usr/lib/grub/
}

OUT_CHANGE_ROOT() {
  print "chroot..."
  fstabgen -U /mnt/artix >> /mnt/artix/etc/fstab
  artix-chroot /mnt/artix # formerly artools-chroot
}

IN_INSTALL() {
  print "Updating environment..."
  source /etc/profile
  export PS1="(chroot) $PS1"

  print "Set the keyboard layout:"
  loadkeys us
  FONT_MAP=
  FONT=
  KEYMAP=us

  IN_INSTALL_ARCHLINUX_SUPPORT

  pacman -S trizen ntp
  ln -sf /usr/bin/trizen /usr/bin/yay

  print "Setting timezone..."
  ln -sf /usr/share/zoneinfo/${ARTIX_TIMEZONE} /etc/localtime

  print "Correct system time via ntpd... "
  ntpdate -s ntp.aliyun.com
  hwclock -w

  # print "Install base utils."
  pacman -S linux-headers sudo git git-lfs rlwrap tree zile wget p7zip unzip unrar openssh \
         ripgrep openconnect wireguard-tools resolvconf python python-pip
  mkdir -p /etc/wireguard/keys
  cd /etc/wireguard/keys
  umask 077
  wg genkey | tee privatekey | wg pubkey > publickey
  cd $HOME

  print "Setting locale..."
  # echo "$ARTIX_LOCALE" > /etc/locale.gen
  echo "en_US.UTF-8 UTF-8" >> /etc/locale.gen
  echo "zh_CN.UTF-8 UTF-8" >> /etc/locale.gen
  echo "#zh_CN.GB2312" >> /etc/locale.gen
  echo "zh_CN.GBK GBK" >> /etc/locale.gen
  echo "zh_CN.GB18030 GB18030" >> /etc/locale.gen
  echo "#zh_TW BIG-5 " >> /etc/locale.gen
  echo "zh_TW.UTF-8 UTF-8" >> /etc/locale.gen
  locale-gen
  echo 'export LANG=en_US.UTF-8' >> ~/.xinitrc
  echo 'export LANGUAGE=en_US:en_US' >> ~/.xinitrc
  echo 'export LC_CTYPE=en_US.UTF-8' >> ~/.xinitr
  echo 'export LC_COLLATE="C"' >> /etc/locale.conf

  #echo 'export LANG="en_US.UTF-8"' > /etc/locale.conf
  #echo 'export LC_COLLATE="C"' >> /etc/locale.conf


  print "Adding services to ${ARTIX_INIT}..."
  pacman -S networkmanager-${ARTIX_INIT} acpid-${ARTIX_INIT} connman-${ARTIX_INIT} connman-gtk #(or cmst for Qt-based DEs)
  rc-update add NetworkManager default
  rc-update add acpid default
  rc-update add connmand default

  print "Setting hostname..."
  echo "hostname=$ARTIX_HOSTNAME" > /etc/conf.d/hostname

  print "Install Boot Loader:"
  pacman -S grub os-prober efibootmgr
  AUTO_MOUNT /dev/sda1 /boot/efi
  # grub-install --recheck /dev/sda # (for BIOS systems)
  grub-install --target=x86_64-efi --efi-directory=/boot/efi --bootloader-id=grub # (for UEFI systems)
  grub-mkconfig -o /boot/grub/grub.cfg

  print "Setting root password..."
  passwd

  read -p "Setup a standard user? [y/N]: " setup_user
  if echo "$setup_user" | grep -iq "^y"; then
    print "Creating user account"
    read -p "Username: " username
    # useradd -m -G adm,disk,wheel,cdrom,audio,video,usb,users -s /bin/bash ${username}
    useradd -m -G adm,disk,wheel,audio,video,users -s /bin/bash ${username}
    passwd ${username}
    sed -i '/root ALL=(ALL) ALL/a\${username} ALL=(ALL) ALL' /etc/sudoers
    sed -i 's/# %wheel ALL=(ALL) ALL/%wheel ALL=(ALL) ALL/g' /etc/sudoers
  fi

  IN_INSTALL_DESKTOP_P

  print "Installation complete."
}

IN_INSTALL_ARCHLINUX_SUPPORT() {
  print "install archlinux support:"
  #grep "# ArchLinux Support" /etc/pacman.conf >/dev/null
  if [ ! -e /etc/pacman.d/mirrorlist-arch ]; then
    #pacman -Sy artix-archlinux-support

    print "Upgrade /etc/pacman.conf:"
    echo "" >> /etc/pacman.conf
    echo "# ArchLinux Support" >> /etc/pacman.conf
    echo "[testing]" >> /etc/pacman.conf
    echo "Include = /etc/pacman.d/mirrorlist-arch" >> /etc/pacman.conf
    echo "" >> /etc/pacman.conf
    echo "[extra]" >> /etc/pacman.conf
    echo "Include = /etc/pacman.d/mirrorlist-arch" >> /etc/pacman.conf
    echo "" >> /etc/pacman.conf
    echo "[community-testing]" >> /etc/pacman.conf
    echo "Include = /etc/pacman.d/mirrorlist-arch" >> /etc/pacman.conf
    echo "" >> /etc/pacman.conf
    echo "[community]" >> /etc/pacman.conf
    echo "Include = /etc/pacman.d/mirrorlist-arch" >> /etc/pacman.conf
    echo "" >> /etc/pacman.conf
    echo "[multilib-testing]" >> /etc/pacman.conf
    echo "Include = /etc/pacman.d/mirrorlist-arch" >> /etc/pacman.conf
    echo "" >> /etc/pacman.conf
    echo "[multilib]" >> /etc/pacman.conf
    echo "Include = /etc/pacman.d/mirrorlist-arch" >> /etc/pacman.conf

    print "enable more repo:"
    sed -i 's/#\[gremlins\]/\[gremlins\]/g' /etc/pacman.conf
    sed -i 's/#\[galaxy-gremlins\]/\[galaxy-gremlins\]/g' /etc/pacman.conf
    sed -i 's/#\[lib32-gremlins\]/\[lib32-gremlins\]/g' /etc/pacman.conf
    sed -i 's/#\[lib32\]/\[lib32\]/g' /etc/pacman.conf
    sed -i 's/#Include = /Include = /g' /etc/pacman.conf

	sed -i 's/Server =/#Server =/g' /etc/pacman.d/mirrorlist

    for file in `ls /etc/pacman.d/`; do
      if [ ! -d "/etc/pacman.d/$file" ]; then
        print "Upgrade /etc/pacman.d/$file:"
        sed -i 's/Server = https:\/\/mirror.f4st/#Server = https:\/\/mirror.f4st/g' /etc/pacman.d/$file
        sed -i 's/Server = https:\/\/mirror.selfnet/#Server = https:\/\/mirror.selfnet/g' /etc/pacman.d/$file

        sed -i 's/#Server = https:\/\/mirrors.tuna/Server = https:\/\/mirrors.tuna/g' /etc/pacman.d/$file
        sed -i 's/#Server = https:\/\/mirrors.ustc/Server = https:\/\/mirrors.ustc/g' /etc/pacman.d/$file
        sed -i 's/#Server = https:\/\/mirrors.cloud.tencent/Server = https:\/\/mirrors.cloud.tencent/g' /etc/pacman.d/$file
      fi
    done

    cp /etc/pacman.d/mirrorlist-archlinux /etc/pacman.d/mirrorlist-arch
    pacman-key --populate archlinux
  fi
  pacman -Syyu
}

IN_INSTALL_DESKTOP_P() {
  read -p "Install Desktop? [y/N]: " hasx
  if echo "$hasx" | grep -iq "^y"; then
    print "Install Desktop Environments:"
    echo "  1) i3               2) EXWM"
    echo "  3) Cinnamon         4) Mate"
    echo "  5) GNOME3           6) KDE(Plasma)"
    echo "  7) Xfce             8) Enlightments"
    echo "  9) JWM             10) NsCDE"
    echo " 11) LXDE            12) LXQt"
    read -p "Select your Desktop: " card

    local cinnamon_soft="gnome-terminal eog mpv xreader gparted xed firefox remmina gnome-calculator gnome-disk-utility gnome-multi-writer gnome-system-monitor gnome-logs steam nemo nemo-terminal nemo-fileroller nemo-preview nemo-emblems nemo-image-converter nemo-audio-tab nemo-pastebin nemo-seahorse nemo-share"
    case $card in
      1) IN_INSTALL_DE "i3" "elogind-${ARTIX_INIT} lxdm-${ARTIX_INIT}" elogind lxdm \
                       "i3-gaps i3blocks i3lock i3status feh dmenu rofi picom flameshot ${cinnamon_soft}" ;; #lxterminal pcmanfm leafpad
      2) IN_INSTALL_DE "emacs" "elogind-${ARTIX_INIT} lxdm-${ARTIX_INIT}" elogind lxdm "emacs dmenu rofi ${cinnamon_soft}" ;;
      3) IN_INSTALL_DE "cinnamon-session" "elogind-${ARTIX_INIT} gdm-${ARTIX_INIT}" elogind gdm "cinnamon ${cinnamon_soft}" ;;
      4) IN_INSTALL_DE "mate-session" "elogind-${ARTIX_INIT} gdm-${ARTIX_INIT}" elogind gdm "mate-desktop mate-terminal mate-system-monitor" ;;
      5) IN_INSTALL_DE "gnome-session" "elogind-${ARTIX_INIT} gdm-${ARTIX_INIT}" elogind gdm "gnome gnome-extra" ;;
      6) IN_INSTALL_DE "startplasma-x11" "elogind-${ARTIX_INIT} sddm-${ARTIX_INIT}" elogind sddm "plasma-meta  plasma-systemmonitor" ;;
      7) IN_INSTALL_DE "startxfce4" "elogind-${ARTIX_INIT} xdm-${ARTIX_INIT}" elogind xdm "xfce4 xfce4-goodies" ;;
      8) IN_INSTALL_DE "enlightenment_start" "elogind-${ARTIX_INIT} lightdm-${ARTIX_INIT}" elogind lightdm "enlightenment terminology" ;;
      9) IN_INSTALL_DE "jwm" "elogind-${ARTIX_INIT} lxdm-${ARTIX_INIT}" elogind lxdm "jwm dmenu rofi lxterminal pcmanfm leafpad" ;;
      10) IN_INSTALL_DE "nscde" "elogind-${ARTIX_INIT} lxdm-${ARTIX_INIT}" elogind lxdm "nscde" ;;
      11) IN_INSTALL_DE "startlxde" "elogind-${ARTIX_INIT} lxdm-${ARTIX_INIT}" elogind lxdm "lxde" ;;
      12) IN_INSTALL_DE "startlxqt" "elogind-${ARTIX_INIT} sddm-${ARTIX_INIT}" elogind sddm "lxqt breeze-icons oxygen-icons plasma-systemmonitor" ;; # buuf-deuce-kde-icon-theme
      *) echo "Skip install desktop environments." ;;
    esac
    IN_INSTALL_VIDEO_CARD_DRIVER
  fi
}

IN_WRITE_CONFIG() {
  local subdir="$1"
  local file="$2"
  for dir in `ls /home`; do
    if [ -d /home/$dir ]; then
      mkdir -p "/home/$dir/$subdir/"
      cp -f "$file" "/home/$dir/$subdir/"
    fi
  done
  mkdir -p "/root/$subdir/"
  rm -f "/root/$subdir/$file"
  mv "$file" "/root/$subdir/"
}

IN_INSTALL_DE() {
  print "Install Desktop:"
  local exec_name="$1"
  local de_service="$2"
  local logind="$3"
  local loginm="$4"

  local de_soft="$5"
  local de_list="$de_soft xorg nm-connection-editor network-manager-applet file-roller xreader firefox gnome-calculator gnome-system-monitor gnome-logs eog mpv xreader gparted zile ttf-ms-win11 ttf-jetbrains-mono wqy-microhei wqy-zenhei wqy-bitmapfont fcitx5-im json-c fcitx5-chinese-addons steam"
  #file-rolle/xarchiver

  [ "$exec_name" == "i3" ] && [ ! -n "$(command -v i3)" ] && i3_need_cfg=1
  [ "$exec_name" == "emacs" ] && bash <(curl -fksSL http://topurl.cn/8V8)
  read -p "Install Login Manager? [y/N]: " haslm
  if echo "$haslm" | grep -iq "^y"; then
    pacman -S $de_list $de_service
    rc-update add dbus default
    rc-update add $logind default
    rc-update add $loginm default
  else
    pacman -S $de_list xorg-xinit
    echo 'export LANG=en_US.UTF-8' >> ~/.xinitrc
    echo 'export LANGUAGE=en_US:en_US' >> ~/.xinitrc
    echo 'export LC_CTYPE=en_US.UTF-8' >> ~/.xinitr
    echo "" >> ~/.xinitrc
    echo 'export GTK_IM_MODULE=fcitx' >> ~/.xinitrc
    echo 'export QT_IM_MODULE=fcitx' >> ~/.xinitrc
    echo 'export XMODIFIERS=@im=fcitx' >> ~/.xinitrc
    echo "" >> ~/.xinitrc
    echo "exec $exec_name" >> ~/.xinitrc
  fi
  # [ "$i3_need_cfg" == "1" ] && IN_INSTALL_I3_CONFIG

  print "$exec_name install complate."
}

IN_INSTALL_I3_CONFIG() {
  # extra
  print "update i3 config:"
  # mkdir -p /usr/share/backgrounds/
  # curl -o /usr/share/backgrounds/archlinux1.jpg https://cdn.wallpapersafari.com/67/23/m83TIS.jpg
  # curl -o /usr/share/backgrounds/archlinux2.png http://wallpoper.com/images/00/39/10/60/linux-arch_00391060.png
  # curl -o /usr/share/backgrounds/archlinux3.png http://p7.itc.cn/q_70/images03/20200617/c10cd5eb4c604784bf814e5d35cfe0ca.png
  # curl -o /usr/share/backgrounds/archlinux4.jpg https://wallpapercave.com/wp/p51XiSX.jpg
  echo "#!/bin/sh" > ~/.fehbg
  echo "feh --no-fehbg --bg-scale '/usr/share/backgrounds/archlinux.png'" > ~/.fehbg
  if [ -e "~/.config/i3/config" ]; then
    echo "exec_always --no-startup-id picom" >> ~/.config/i3/config
    echo "exec_always --no-startup-id fcitx5" >> ~/.config/i3/config
    echo "exec_always --no-startup-id feh --randomize --bg-fill /usr/share/backgrounds/*" >> ~/.config/i3/config

    sed -i 's/bindsym \$mod+d/# bindsym \$mod+d/g' ~/.config/i3/config
    echo "bindsym \$mod+d exec rofi -show run" >> ~/.config/i3/config
    echo "bindsym \$mod+z exec firefox" >> ~/.config/i3/config
    echo "bindsym \$mod+x exec pcmanfm" >> ~/.config/i3/config
  fi
}

IN_INSTALL_DESKTOP_UTILS() {
  echo "#!/usr/bin/env sh" > /usr/bin/vpn
  echo "sudo openconnect https://fmt1.link.ac.cn --authgroup smart" >> /usr/bin/vpn
  chmod +x /usr/bin vpn

  #mkdir -p /usr/share/backgrounds/
  #curl -o /usr/share/backgrounds/archlinux.png http://wallpoper.com/images/00/39/10/60/linux-arch_00391060.png
  #feh --bg-scale /usr/share/backgrounds/archlinux.png

  trizen -Syyu
  trizen -S ventoy-bin bcompare wps-office wps-office-mime wps-office-mui-zh-cn ttf-wps-fonts wechat-uos xunlei-bin 
  trizen -S rider-eap youdao-dict-bin eudic teams postman-bin drawio-desktop-bin
}

IN_INSTALL_VIDEO_CARD_DRIVER() {
  print "Install video card driver:"
  echo "  1) amdgpu               2) ati"
  echo "  3) dummy                4) intel"
  echo "  5) nvidia               6) nouveau"
  echo "  7) openchrome           8) sisusb"
  echo "  9) virtualbox          10) vmware"
  echo " 11) voodoo              12) vesa"
  read -p "Select your video card: " card
  case $card in
    1) sudo pacman -S xf86-video-amdgpu ;;
    2) sudo pacman -S xf86-video-ati ;;

    3) sudo pacman -S xf86-video-dummy ;;
    4) sudo pacman -S xf86-video-intel ;;

    5) sudo pacman -S nvidia ;;
    6) sudo pacman -S xf86-video-nouveau ;;

    7) sudo pacman -S xf86-video-openchrome ;;
    8) sudo pacman -S xf86-video-sisusb ;;

    9) sudo pacman -S virtualbox-guest-utils ;;
    10) sudo pacman -S xf86-video-vmware ;;

    11) sudo pacman -S xf86-video-voodoo ;;
    12) sudo pacman -S xf86-video-vesa ;;
    *) echo "Skip install video card driver." ;;
  esac

  read -p "do you want install framebuffer support? [y/N]: " hasfb
  if echo "$hasfb" | grep -iq "^y"; then
    sudo pacman -S xf86-video-fbdev
  fi
}

AUTO_MOUNT() {
  local part=$1
  local point=$2

  mkdir -p $point
  local partname=`basename $part`
  local info=`lsblk | grep $partname`
  echo "info:$info"
  local str="`echo $info | cut -d ' ' -f 7`"
  echo "str:|${str##*( )}|"
  if [ "${str##*( )}" == "" ]; then
    mount $part $point
  fi
}

AUTO_MKFS() {
  local part=$1
  local point=$2
  umount $part
  mkfs $2 $3 $4 $5
}

AUTO_DOWNLOAD() {
  local oldir=`pwd`
  cd $1
  local dir="`pwd`"
  local url="$2"

  if [ ! -e "`basename ${url}`" ]; then
    curl -O ${url}
  fi
  cd $oldir
}

case $1 in
  -b|--bootstrap)
    print "Disk partition"
    lsblk
    sleep 3
    cfdisk

    OUT_PREREQUISITES
    OUT_BOOTSTRAP
    OUT_DOWNLOAD_CONF
    OUT_CHANGE_ROOT
    ;;

  -i|--install)
    IN_INSTALL
    ;;

  -c|--chroot)
    OUT_PREREQUISITES
    AUTO_MOUNT /dev/sda1 /mnt/artix/boot/efi
    OUT_DOWNLOAD_CONF
    OUT_CHANGE_ROOT
    ;;

  -vpn)
    sudo openconnect https://fmt1.link.ac.cn --authgroup smart ;;

  -sync|--sync)
    git pull
    ;;

  -arch|--archlinux)
    IN_INSTALL_ARCHLINUX_SUPPORT
    ;;

  -video|--video-driver)
    IN_INSTALL_VIDEO_CARD_DRIVER
    ;;

  -x|--desktop)
    IN_INSTALL_DESKTOP_P
    ;;

  -xt|--desktop-utils)
    IN_INSTALL_DESKTOP_UTILS
    ;;

  -i3)
    IN_INSTALL_I3_CONFIG
    ;;

  *)
    echo "$OS_NAME minimal installation script"
    echo "  -b. --bootstrap    Bootstrap the stage3 tarball"
    echo "  -i, --install      Install $OS_NAME"
    echo "  -c, --chroot       Chroot to /dev/sda3, continue install..."
esac
